package com.share.alibaba.auser.config;

import feign.Logger;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

import java.util.stream.Collectors;

/**
 * openfeign调用的拦截器
 */
@Slf4j
@Configuration
public class FeignClientConfig implements RequestInterceptor {
    @Value("${spring.application.name}")
    private String applicationName;

    /*
     * NONE-无记录（DEFAULT）;
     * BASIC-只记录请求方法和URL以及响应状态代码和执行时间;
     * HEADERS-记录基本信息以及请求和响应标头;
     * FULL-记录请求和响应的头文件，正文和元数据;
     */
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    /**
     * 新版本必须配置HttpMessageConverters,否则消息feignclient只会调用fallback（解决方法方式一:删除fallback,方式二:添加HttpMessageConverters）
     * 老版本不用配置
     * @param converters
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
        return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
    }

    /**
     * 配置FeignClient拦截器,只有在发起了feign调用时,才会调用这个方法
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        String url = requestTemplate.path();
        Request.Body body = requestTemplate.requestBody();
        if (body != null && body.asString() != null) {
            log.info("applicationName={}发起feign请求,url={},body={}", applicationName, url, body.asString());
        }
    }
}
